package team.seekers.skill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import team.seekers.skill.common.enums.RoleEnum;
import team.seekers.skill.entity.dao.User;
import team.seekers.skill.entity.dao.UserSeekSkill;
import team.seekers.skill.entity.vo.fore.add.UserAddVO;
import team.seekers.skill.mapper.UserMapper;
import team.seekers.skill.service.UserService;
import org.springframework.stereotype.Service;
import team.seekers.skill.service.UserSeekSkillService;
import team.seekers.skill.common.utils.SkillUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hbc
 * @since 2021-02-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserSeekSkillService userSeekSkillService;

    @Override
    public User selectByName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User one = getOne(wrapper);
        return one;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean save(UserAddVO userAddVO) {
        User user = new User();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(userAddVO.getPassword());
        userAddVO.setPassword(encode);
        BeanUtils.copyProperties(userAddVO, user);
        user.setRole(RoleEnum.USER);
        boolean save = save(user);
        if (!save){
            return false;
        }
        //维护学习记录表
        UserSeekSkill userSeekSkill = new UserSeekSkill();
        userSeekSkill.setUserId(user.getId());
        boolean save2 = userSeekSkillService.save(userSeekSkill);
        if(!save2){
            return false;
        }
        return true;
    }
}
